package net.paoding.rose.jade.statement.jexl.analysis.impl;


import net.paoding.rose.jade.statement.jexl.Jexl3Execute;
import net.paoding.rose.jade.statement.jexl.analysis.Analysis;

import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 变量字段解析
 * @author fusheng.zhang
 * @date 2022-03-08 10:30:03
 */
public class VariableAnalysis implements Analysis {

    /**
     * 变量文本
     */
    private final String variableStr;
    private final boolean isIn;

    public VariableAnalysis(String variableStr, boolean isIn) {
        this.isIn = isIn;
        this.variableStr = variableStr;
    }

    @Override
    public String toString() {
        return variableStr;
    }

    @Override
    public void execute(Jexl3Execute jexl3Execute) {
        Object o = jexl3Execute.execute(jexl3Execute.getParams(), jexl3Execute.getConstantParams(), toStr(variableStr));
        if (Objects.nonNull(o)) {
            if (isIn && ((o instanceof Collection) || (o.getClass().isArray() && o.getClass() != byte[].class))) {
                Collection<?> collection = asCollection(o);
                if (collection.isEmpty()) {
                    jexl3Execute.setStr("NULL");
                } else {
                    collection.forEach(jexl3Execute::setValue);
                    jexl3Execute.setStr(collection.stream().map(c -> "?").collect(Collectors.joining(",")));
                }
            } else {
                jexl3Execute.setValue(o).setStr("?");
            }
        } else {
            jexl3Execute.setValue(null).setStr("?");
        }
    }
}
